package com.gqz.equip.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.gqz.equip.service.IExportExcelService;
import com.gqz.equip.service.ITEnWzEquipBqService;
import com.gqz.equip.vo.ExportParamVo;
import com.gqz.equip.vo.TEnWzEquipBqVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.util.Base64;
import java.util.List;

/**
 * @Description
 **/
@Service
@Slf4j
public class ExportServiceImpl implements IExportExcelService {

    private RestTemplate restTemplate = new RestTemplate();

    private static String DEFAULT_FILE_NAME = "导出文件";

    @Resource
    private ITEnWzEquipBqService itEnWzEquipBqService;

    @Override
    public void exportPage(ExportParamVo vo, HttpServletResponse response) throws IOException {
        OutputStream os = null;
        HSSFWorkbook workbook = new HSSFWorkbook();

        try {
            String fileName = (vo.getFileName() == null ? DEFAULT_FILE_NAME : URLDecoder.decode(vo.getFileName(), "UTF-8")) + ".xlsx";

            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", (new StringBuilder()).append("attachment; filename=").append(fileName).toString());
            os = response.getOutputStream();

            //标题和页码
            CellStyle titleStyle = workbook.createCellStyle();
            // 设置字体样式
            HSSFFont titleFont = workbook.createFont();
            // 字体高度
            titleFont.setFontHeightInPoints((short) 12);
            // 字体样式
            titleFont.setFontName("黑体");
//            titleFont.setColor(HSSFColor.toHSSFColor());
            titleStyle.setFont(titleFont);
            titleStyle.setFont(titleFont);
            titleStyle.setBorderBottom(BorderStyle.THIN); //下边框
            titleStyle.setBorderLeft(BorderStyle.THIN);//左边框
            titleStyle.setBorderTop(BorderStyle.THIN);//上边框
            titleStyle.setBorderRight(BorderStyle.THIN);//右边框
            titleStyle.setAlignment(HorizontalAlignment.CENTER); // 居中
            titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            //创建sheet
            HSSFSheet sheet = workbook.createSheet();

            // 在sheet中添加标题行// 行数从0开始
            int rowNum = 0;
            Row thRow = sheet.createRow(rowNum);
            for (int i = 0; i < vo.getColumnNameList().size(); i++) {
                Cell cell = thRow.createCell(i);
                sheet.setColumnWidth(i, vo.getColumnWidthList().get(i) * 60);
                cell.setCellValue(vo.getColumnNameList().get(i));
                cell.setCellStyle(titleStyle);
            }

            rowNum++;

            JSONArray records = queryDataList(vo);
            // log.info("导出数据量：{}", resultData.getJSONArray("records").size());

            //JSONArray records = resultData.getJSONArray("records");
            Drawing patriarch = sheet.createDrawingPatriarch();
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
            cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
            cellStyle.setBorderTop(BorderStyle.THIN);//上边框
            cellStyle.setBorderRight(BorderStyle.THIN);//右边框
            cellStyle.setAlignment(HorizontalAlignment.CENTER); // 居中
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            for (int i = 0; i < records.size(); i++) {
                Row tdRow = sheet.createRow(rowNum);
                JSONObject item = records.getJSONObject(i);
                tdRow.setHeight((short) 800);
                for (int j = 0; j < vo.getColumnNameList().size(); j++) {
                    String key = vo.getColumnCodeList().get(j);
                    Cell cell = tdRow.createCell(j);
                    cell.setCellStyle(cellStyle);
                    String tempValue = item.getString(key) == null ? "" : item.getString(key);
                    if (tempValue.contains("base64")) {
                        Base64.Decoder decoder = Base64.getDecoder();
                        byte[] bytes1 = decoder.decode(tempValue.replace("data:image/png;base64,", ""));
                        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                        try {
                            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
                            // InputStream inputStream = getClass().getResourceAsStream("/a.jpg");
                            //加入图像缓冲区
                            BufferedImage buffer_Img = ImageIO.read(bais);
                            // 写入
                            ImageIO.write(buffer_Img, "jpg", byteArrayOut);
                        } catch (IOException e) {
                            System.out.println("写入出错");
                            e.printStackTrace();
                        }
                        //图片位置 col1 列下标
                        HSSFClientAnchor anchor = new HSSFClientAnchor(100, 5, 500, 255, (short) j, i + 1, (short) j, i + 1);
                        anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_DONT_RESIZE);
                        // 插入图片
                        patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
                    } else {
                        // 为当前列赋值
                        cell.setCellValue(tempValue);
                    }
                }
                rowNum++;
            }
            workbook.write(os);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            workbook.close();
            os.close();
        }
    }

    /**
     * 通过restTemplate调用接口
     *
     * @param vo vo
     * @return JSONObject
     */
    private JSONObject queryData(ExportParamVo vo) {
        JSONObject retJso = new JSONObject();

        HttpHeaders headers = new HttpHeaders();
        headers.add("token", "8a812897493378a0014956752855660f-0123456789");
        headers.add("Content-Type", "application/json;charset=UTF-8");
        // 参数
        JSONObject params = vo.getQueryParams();
        // 总数作为分页数量
        params.put("pageSize", vo.getDataNum());
        HttpEntity<JSONObject> httpEntity = new HttpEntity<JSONObject>(params, headers);

        ResponseEntity<JSONObject> responseEntity = null;
        List<TEnWzEquipBqVo> vos = itEnWzEquipBqService.getListEwm(JSONObject.parseObject(params.toJSONString(), TEnWzEquipBqVo.class));
        if (vos.size() > 0) {
            // retJso = responseEntity.getBody().getJSONObject("data");
            retJso = JSONObject.parseObject(vos.toString());
        }
        return retJso;
    }

    /**
     * 通过restTemplate调用接口
     *
     * @param vo vo
     * @return JSONObject
     */
    private JSONArray queryDataList(ExportParamVo vo) {
        JSONArray retJso = new JSONArray();

        HttpHeaders headers = new HttpHeaders();
        headers.add("token", "8a812897493378a0014956752855660f-0123456789");
        headers.add("Content-Type", "application/json;charset=UTF-8");
        // 参数
        JSONObject params = vo.getQueryParams();
        // 总数作为分页数量
        params.put("pageSize", vo.getDataNum());
        HttpEntity<JSONObject> httpEntity = new HttpEntity<JSONObject>(params, headers);
        ResponseEntity<JSONObject> responseEntity = null;
        List<TEnWzEquipBqVo> vos = itEnWzEquipBqService.getListEwm(JSONObject.parseObject(params.toJSONString(), TEnWzEquipBqVo.class));
        if (vos.size() > 0) {
            retJso = JSONArray.parseArray(JSON.toJSONString(vos));
        }
        return retJso;
    }

    public void base64ToImg(String base64, String targetPath) {
        File file = null;
        FileOutputStream fops = null;
        base64 = base64.replace("data:image/jpeg;base64,", "");
        byte[] buff = DatatypeConverter.parseBase64Binary(base64);
        try {
            fops = new FileOutputStream(new File(targetPath));
            fops.write(buff);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("--------------------------------" + "图片转换完成" + "--------------------------------");
    }
}
